<template>
  <s-modal
    :title="title"
    :visible="visible"
    :width="properties.width"
    :confirm-loading="confirmLoading"
    :closable="!confirmLoading"
    @cancel="
      () => {
        if (!confirmLoading) {
          visible = false
        }
      }
    "
  >
    <template #footer>
      <s-button
        key="back"
        @click="
          () => {
            if (!confirmLoading) {
              visible = false
            }
          }
        "
      >
        取消
      </s-button>
      <s-button
        v-if="!disable"
        key="submit"
        type="primary"
        :loading="confirmLoading"
        @click="$save"
      >
        {{ okText }}
      </s-button>
    </template>
    <div :style="{ height: properties.height }">
      <s-scroll>
        <s-form ref="form" :value="formValue">
          <s-dynamic-form
            :form="formValue"
            :items="items"
            :disable-item="disable"
            @change="$itemChange"
          />
          <slot />
        </s-form>
      </s-scroll>
    </div>
  </s-modal>
</template>

<script>
export default {
  name: 'FlowStartDialog',
  props: {
    disable: {
      type: Boolean,
      required: false,
      default: false
    },
    title: {
      type: String,
      required: false,
      default: '详情'
    }
  },
  data() {
    return {
      okText: '保存',
      confirmLoading: false,
      formValue: {},
      visible: false,
      items: [],
      properties: {
        width: '0px',
        height: '0px'
      }
    }
  },

  methods: {
    $itemChange(val) {
      this.$emit('change', val)
    },
    open() {
      this.$loading(false)
      this.visible = true
    },
    init(url, data, onInit) {
      this.$loading(true)
      const that = this
      this.$api
        .GET(url, data)
        .then((res) => {
          this.$loading(false)
          if (!res.data) {
            this.$message.warn('数据不存在')
          } else {
            const json = JSON.parse(res.data)
            that.properties.height = json.properties.height
            that.properties.width = json.properties.width
            that.items = json.data
            that.formValue = {}
            if (onInit) {
              onInit(that)
            } else {
              that.open()
            }
          }
        })
        .catch(() => {
          this.$loading(false)
        })
    },
    resetLoading() {
      this.confirmLoading = false
    },
    close() {
      this.visible = false
      this.confirmLoading = false
    },
    $save() {
      const form = this.$refs.form
      form.validate((values, fullValue) => {
        this.confirmLoading = true
        this.$emit('save', values, fullValue)
      })
    }
  }
}
</script>

<style lang="less" scoped></style>
